Component({
  properties: {
    totalSeconds: {
      type: Number,
      value: 90,
      observer(newVal) {
        this.reset(newVal);
      }
    }
  },

  data: {
    remain: 0,
    timeStr: '01:30',
    timer: null,
    animationTimeout: null
  },

  lifetimes: {
    ready() {
      const { totalSeconds } = this.properties;
      this.reset(totalSeconds);
      this.startCountdown();
    },
    detached() {
      this.clear();
    }
  },

  methods: {
    reset(totalSeconds) {
      // 先清除现有的定时器
      this.clear();
      
      // 重置数据
      this.setData({ 
        remain: totalSeconds,
        timeStr: this.formatTime(totalSeconds),
        timer: null,
        animationTimeout: null
      });
      
      // 只有当 totalSeconds 大于0时才开始倒计时
      if (totalSeconds > 0) {
        // 重新初始化canvas
        this.initCanvas();
        // 重新开始倒计时
        this.startCountdown();
      }
    },

    clear() {
      if (this.data.timer) {
        clearInterval(this.data.timer);
        this.setData({ timer: null });
      }
      if (this.data.animationTimeout) {
        clearTimeout(this.data.animationTimeout);
        this.setData({ animationTimeout: null });
      }
    },
    formatTime(seconds) {
      const m = Math.floor(seconds / 60);
      const s = seconds % 60;
      const mm = m < 10 ? '0' + m : m;
      const ss = s < 10 ? '0' + s : s;
      return `${mm}:${ss}`;
    },

    initCanvas() {
      const query = this.createSelectorQuery();
      query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {
        if (!res || !res[0] || !res[0].node) return;

        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio;

        canvas.width = 16 * dpr;
        canvas.height = 16 * dpr;
        ctx.scale(dpr, dpr);

        this.drawAnimatedCircle(ctx, canvas);
      });
    },

    drawAnimatedCircle(ctx, canvas) {
      const centerX = 8; // 圆心 X
      const centerY = 8; // 圆心 Y
      const radius = 7;  // 半径
      const startAngle = (3 * Math.PI) / 2; // 初始角度 270°
      const fullCircle = Math.PI * 2;       // 完整一圈弧度
      const duration = this.properties.totalSeconds * 1000; // 动画总时长（毫秒）
      const fps = 60;                       // 帧率（每秒帧数）
      const interval = 1000 / fps;          // 每帧间隔时间（毫秒）
      let elapsed = 0;
    
      // 清除之前的动画定时器
      if (this.data.animationTimeout) {
        clearTimeout(this.data.animationTimeout);
      }
    
      // 创建渐变色
      const gradient = ctx.createLinearGradient(
        centerX - radius,
        centerY - radius,
        centerX + radius,
        centerY + radius
      );
      gradient.addColorStop(0, '#04DFCF');
      gradient.addColorStop(1, '#51A3F4');
    
      const animate = () => {
        // 检查组件是否还存在
        if (!this.data.animationTimeout) return;
        
        elapsed += interval;
        const progress = Math.min(elapsed / duration, 1);
    
        ctx.clearRect(0, 0, 16, 16);
    
        // 绘制整个圆
        ctx.beginPath();
        ctx.arc(centerX, centerY, radius, 0, fullCircle);
        ctx.fillStyle = gradient;
        ctx.fill();
    
        // 设置擦除模式
        ctx.globalCompositeOperation = 'destination-out';
    
        const currentAngle = startAngle + fullCircle * progress;
    
        // 绘制裁剪区域扇形
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, radius, startAngle, currentAngle);
        ctx.closePath();
        ctx.fill();
    
        // 恢复默认绘制模式
        ctx.globalCompositeOperation = 'source-over';
    
        if (progress < 1) {
          this.setData({
            animationTimeout: setTimeout(animate, interval)
          });
        }
      };
    
      this.setData({
        animationTimeout: setTimeout(animate, interval)
      });
    },
    

    updateTimeStr(seconds) {
      const timeStr = this.formatTime(seconds);
      this.setData({ timeStr });
    },

    startCountdown() {
      const { totalSeconds } = this.properties;
      // 如果时间为0或负数，不启动倒计时
      if (totalSeconds <= 0) return;
      
      // 确保清除之前的定时器
      if (this.data.timer) {
        clearInterval(this.data.timer);
      }
      
      let remain = totalSeconds;
    
      this.updateTimeStr(remain);
    
      const timer = setInterval(() => {
        remain -= 1;
        if (remain >= 0) {
          this.updateTimeStr(remain);
        } else {
          clearInterval(timer);
          // 更新组件内部的 timer 引用为 null
          this.setData({ timer: null });
          this.triggerEvent('finish');
        }
      }, 1000);
    
      this.setData({ timer });
    }
  }
});
